package com.jbh.request.utils

import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.Locale

/**
 * Created by zbsdata on 2016/12/12.
 */
object MD5Util {
    /**
     * MD5加密
     * @param message 要进行MD5加密的字符串
     * @return 加密结果为32位字符串
     */
    fun getMD5(message: String): String {
        val md5StrBuff = StringBuffer()
        try {
            val messageDigest = MessageDigest.getInstance("MD5")
            messageDigest.reset()
            messageDigest.update(message.toByteArray(charset("UTF-8")))

            val byteArray = messageDigest.digest()
            for (i in byteArray.indices) {
                if (Integer.toHexString(0xFF and byteArray[i].toInt()).length == 1) md5StrBuff.append(
                    "0"
                ).append(
                    Integer.toHexString(0xFF and byteArray[i].toInt())
                )
                else md5StrBuff.append(Integer.toHexString(0xFF and byteArray[i].toInt()))
            }
        } catch (e: Exception) {
            throw RuntimeException()
        }
        return md5StrBuff.toString().lowercase(Locale.getDefault())
    }

    /**
     * MD5加密
     * @param message 要进行MD5加密的字符串
     * @return 加密结果为32位字符串
     */
    fun MD5(message: String): String {
        val md5StrBuff = StringBuffer()
        try {
            val messageDigest = MessageDigest.getInstance("MD5")
            messageDigest.reset()
            messageDigest.update(message.toByteArray(charset("UTF-8")))

            val byteArray = messageDigest.digest()
            for (i in byteArray.indices) {
                if (Integer.toHexString(0xFF and byteArray[i].toInt()).length == 1) md5StrBuff.append(
                    "0"
                ).append(
                    Integer.toHexString(0xFF and byteArray[i].toInt())
                )
                else md5StrBuff.append(Integer.toHexString(0xFF and byteArray[i].toInt()))
            }
        } catch (e: Exception) {
            throw RuntimeException()
        }
        return md5StrBuff.toString()
    }

    fun getMd5Value(sSecret: String): String {
        try {
            val bmd5 = MessageDigest.getInstance("MD5")
            bmd5.update(sSecret.toByteArray())
            var i: Int
            val buf = StringBuffer()
            val b = bmd5.digest()
            for (offset in b.indices) {
                i = b[offset].toInt()
                if (i < 0) i += 256
                if (i < 16) buf.append("0")
                buf.append(Integer.toHexString(i))
            }
            return buf.toString()
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return ""
    }
}


